import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        int[]array = {1,9,2,8,3,7,4,6,5};
        //bubbleSort(array);
        //selectSort(array);
        //insertSort(array);
        shellSort(array);
        System.out.println(Arrays.toString(array));
    }

    private static void shellSort(int[] array) {
        int gap = array.length;
        while(gap>1){
            gap/=2;
            insertSort1(array,gap);
        }
    }

    private static void insertSort1(int[] array, int gap) {
        for (int i = gap; i < array.length; i++) {
            int j = i-gap;
            int tmp = array[i];
            for (; j >= 0; j-=gap) {
                if(array[j]>tmp){
                    array[j+gap] = array[j];
                }else{
                    break;
                }
            }
            array[j+gap] = tmp;
        }
    }


    private static void insertSort(int[] array) {
        for (int i = 1; i < array.length; i++) {
           int j = i-1;
           int tmp = array[i];
            for (; j >= 0; j--) {
                if(array[j]>tmp){
                    array[j+1] = array[j];
                }else{
                    break;
                }
            }
            array[j+1] = tmp;
        }
    }


    private static void selectSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int minIndex = i;
            for (int j = i+1; j < array.length; j++) {
               if(array[j]<array[minIndex]){
                   minIndex = j;
               }
            }
            swap(array,i,minIndex);
        }
    }

    private static void bubbleSort(int[] array) {
        for (int i = 0; i < array.length-1 ; i++) {
            boolean flag = false;
            for (int j = 0; j < array.length-1-i; j++) {
                if(array[j]> array[j+1]){
                    flag = true;
                    swap(array,j,j+1);
                }
            }
            if(!flag)
                 break;
        }
    }

    private static void swap(int[] array, int j, int i) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
}
